
import numpy as np
from numpy.core.fromnumeric import shape
import pandas as pd
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
import numpy.matlib
def stdError_func(y_test, y):
    return np.sqrt(np.mean((y_test-y)**2))
def R2_1_func(y_test, y):
    return 1-((y_test-y)**2).sum() / ((y.mean() - y)**2).sum()
def R2_2_func(y_test, y):
    y_mean = np.array(y)
    y_mean[:] = y.mean()
    return 1 - stdError_func(y_test, y) / stdError_func(y_mean, y)


def lin_fit(x,y,intercept=True):

    cft = linear_model.LinearRegression(fit_intercept=intercept)
    #print(x.shape)
    cft.fit(x, y) #

    print("\nmodel coefficients", cft.coef_[0])
    print("model intercept", cft.intercept_[0])


    predict_y =  cft.predict(x)
    strError = stdError_func(predict_y, y)
    R2_1 = R2_1_func(predict_y, y)
    R2_2 = R2_2_func(predict_y, y)
    score = cft.score(x, y) ##sklearn中自带的模型评估，与R2_1逻辑相同

    print('strError={:.2f}, R2_1={:.2f},  R2_2={:.2f}, clf.score={:.2f}'.format(
        strError,R2_1,R2_2,score))
    return cft.coef_[0], cft.intercept_[0]

filename = "data.csv"
df= pd.read_csv(filename, engine='python')
xs = np.array(df.iloc[:,0:3].values)#x,y,z
#print(xs)
u = np.array(df.iloc[:,3:4].values)
#print(u)
v = np.array(df.iloc[:,4:5].values)
#print(v)
x_, y_ = np.shape(xs)
ones = np.ones(shape=[x_, 1])
RT = np.zeros(shape=[4,4])

a = np.ones(shape=[3,4])
[a[2][0], a[2][1], a[2][2]], a[2][3] = lin_fit(xs, ones, True)
[a[1][0], a[1][1], a[1][2]], a[1][3] = lin_fit(xs, v, True)
[a[0][0], a[0][1], a[0][2]], a[0][3] = lin_fit(xs, ones, True)
###############
fx = 1
cx = 2
fy = 1
cy = 5
###############
RT[3][3] = 1
RT[0] = (a[0] - cx*a[2])/fx
RT[1] = (a[1] - cy*a[2])/fy
print('*********RT**********')
print(RT)


